<script setup>
import orderAPI from '../api/order_api.js'
import userAPI from '../api/user_api.js'  // 引入用户API
import { ref, onMounted, computed } from "vue";
import {
  ElMessageBox,
  ElMessage,
  ElPagination,
  ElTable,
  ElTableColumn,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElButton,
  ElSelect,
  ElOption,
  ElTag,
  ElPopover
} from 'element-plus';
import lodash from 'lodash';

// 表格数据 & 分页数据
const tableData = ref([]);
const total = ref(0);
const loading = ref(false);  // 添加加载状态

// 用户数据
const users = ref([]);  // 存储用户列表

// 查询条件
const searchObj = ref({
  current: 1,
  limit: 10,
  order_no: '',
  user_id: '',
  order_status: '',
});

// 新增/编辑弹窗绑定对象
const obj = ref({});
// 弹窗显隐控制
const editWinVisible = ref(false);
const addWinVisible = ref(false);

// 表单显示的用户名称
const formUserName = computed(() => {
  return users.value.find(item => item.id === obj.value.user_id)?.name || ''
})

// 页面加载时查询数据
onMounted(async () => {
  await Promise.all([search(), loadUsers()]);  // 同时加载订单和用户数据
});

// 通用查询方法
const search = async () => {
  loading.value = true;
  try {
    const result = await orderAPI.page(searchObj.value);
    tableData.value = result.data || [];
    total.value = result.count || 0;
  } catch (error) {
    ElMessage.error('获取订单数据失败');
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// 加载用户数据
const loadUsers = async () => {
  try {
    const result = await userAPI.page({ current: 1, limit: 100 });
    users.value = result.data || [];
  } catch (error) {
    ElMessage.error('获取用户数据失败');
    console.error(error);
  }
}

// 分页改变（条数切换、页码切换）
const handleSizeChange = () => {
  search();
};
const handleCurrentChange = () => {
  search();
};

// 点击查询按钮
const handlerSearch = async () => {
  searchObj.value.current = 1;
  await search();
};

// 新增弹窗 - 取消
const addCancel = () => {
  obj.value = {};
  addWinVisible.value = false;
};
// 新增弹窗 - 提交
const addCommit = async () => {
  try {
    await orderAPI.add(obj.value);
    await search();
    addWinVisible.value = false;
    obj.value = {};
    ElMessage.success('新增订单成功');
  } catch (error) {
    ElMessage.error('新增订单失败');
    console.error(error);
  }
};

// 编辑弹窗 - 取消
const editCancel = () => {
  obj.value = {};
  editWinVisible.value = false;
};
// 编辑弹窗 - 提交
const editCommit = async () => {
  try {
    await orderAPI.edit(obj.value);
    await search();
    editWinVisible.value = false;
    ElMessage.success('编辑订单成功');
  } catch (error) {
    ElMessage.error('编辑订单失败');
    console.error(error);
  }
};

// 打开新增弹窗
const handleAdd = () => {
  obj.value = {};
  addWinVisible.value = true;
};

// 打开编辑弹窗（复制行数据）
const handleEdit = (index, row) => {
  const { deleted, ...rowWithoutDeleted } = row; // 若有 deleted 字段则剔除
  obj.value = lodash.clone(rowWithoutDeleted);
  editWinVisible.value = true;
};

// 删除操作
const handleDelete = (index, row) => {
  ElMessageBox.confirm(
      '确认删除该行数据吗？',
      '删除提示',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'error',
      }
  )
      .then(async () => {
        try {
          await orderAPI.del(row.id);
          searchObj.value.current = 1;
          await search();
          ElMessage.success('删除订单成功');
        } catch (error) {
          ElMessage.error('删除订单失败');
          console.error(error);
        }
      })
      .catch(() => {});
};

// 确认订单状态（改为已确认）
const confirmOrder = async (row) => {
  if (row.order_status === 1) {
    ElMessageBox.alert('该订单已确认', '提示', {
      confirmButtonText: '确定',
    });
    return;
  }

  if (row.order_status === 2) {
    ElMessageBox.alert('已取消的订单不能确认', '提示', {
      confirmButtonText: '确定',
    });
    return;
  }

  ElMessageBox.confirm(
      '确认将订单状态改为已确认吗？',
      '确认提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        try {
          await orderAPI.edit({
            id: row.id,
            order_status: 1
          });
          await search();
          ElMessage.success('订单已确认');
        } catch (error) {
          ElMessage.error('操作失败');
          console.error(error);
        }
      })
      .catch(() => {});
};

// 取消订单（状态改为2）
const cancelOrder = async (row) => {
  if (row.order_status !== 0) {
    ElMessageBox.alert('只有未确认的订单可以取消', '提示', {
      confirmButtonText: '确定',
    });
    return;
  }

  ElMessageBox.confirm(
      '确认要取消该订单吗？',
      '取消提示',
      {
        confirmButtonText: '确认取消',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        try {
          await orderAPI.edit({
            id: row.id,
            order_status: 2 // 2表示已取消状态
          });
          ElMessage.success('订单已取消');
          await search();
        } catch (error) {
          ElMessage.error('操作失败');
          console.error(error);
        }
      })
      .catch(() => {});
};
</script>

<template>
  <!-- 搜索表单 -->
  <el-form :inline="true" :model="searchObj" class="demo-form-inline" style="margin-top:10px ">
    <el-form-item label="订单编号">
      <el-input v-model="searchObj.order_no" placeholder="请输入订单编号" clearable />
    </el-form-item>
    <el-form-item label="客户ID">
      <el-input v-model="searchObj.user_id" placeholder="请输入客户ID" clearable />
    </el-form-item>
    <el-form-item label="订单状态" style="width: 200px;">
      <el-select v-model="searchObj.order_status" placeholder="全部状态" clearable>
        <el-option label="未确认" value="0"></el-option>
        <el-option label="已确认" value="1"></el-option>
        <el-option label="已取消" value="2"></el-option>
      </el-select>
    </el-form-item>
  </el-form>

  <!-- 查询、新增按钮 -->
  <el-form :inline="true" style="margin-bottom: 10px;">
    <el-form-item>
      <el-button type="primary" @click="handlerSearch">查询</el-button>
    </el-form-item>
    <!-- <el-form-item>
      <el-button type="primary" @click="handleAdd">新增</el-button>
    </el-form-item> -->
  </el-form>

  <!-- 订单表格 -->
  <el-table
      :data="tableData"
      style="width: 100%"
      v-loading="loading"
      border
      stripe
  >
    <el-table-column label="ID" width="80">
      <template #default="scope">
        <el-popover effect="light" trigger="hover" placement="top" width="auto">
          <template #default>
            <div>id: {{ scope.row.id }}</div>
          </template>
          <template #reference>
            <el-tag>{{ scope.row.id }}</el-tag>
          </template>
        </el-popover>
      </template>
    </el-table-column>
    <el-table-column label="订单编号" width="160">
      <template #default="scope">
        <el-tag>{{ scope.row.order_no }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="客户ID" width="80">
      <template #default="scope">
        <el-popover effect="light" trigger="hover" placement="top" width="auto">
          <template #default>
            <div>user_id: {{ scope.row.user_id }}</div>
          </template>
          <template #reference>
            <el-tag type="info">{{ scope.row.user_id }}</el-tag>
          </template>
        </el-popover>
      </template>
    </el-table-column>
    <!-- 新增客户名列 -->
    <el-table-column label="客户名" width="150" align="center">
      <template #default="scope">
        <el-popover effect="light" trigger="hover" placement="top" width="auto">
          <template #default>
            <div>客户名: {{ users.find(u => u.id === scope.row.user_id)?.name }}</div>
          </template>
          <template #reference>
            <el-tag>{{ users.find(u => u.id === scope.row.user_id)?.name || '未知客户' }}</el-tag>
          </template>
        </el-popover>
      </template>
    </el-table-column>
    <el-table-column label="订单总金额" width="120">
      <template #default="scope">
        <el-tag>{{ scope.row.total_amount }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="订单状态" width="100">
      <template #default="scope">
        <el-tag
            :type="scope.row.order_status === 1 ? 'success' :
               scope.row.order_status === 2 ? 'danger' : 'info'"
        >
          {{ scope.row.order_status === 1 ? '已确认' :
            scope.row.order_status === 2 ? '已取消' : '未确认' }}
        </el-tag>
      </template>
    </el-table-column>
    <el-table-column label="收货地址" width="140">
      <template #default="scope">
        <el-tag style="white-space: normal; word-break: break-all;">{{ scope.row.shipping_address }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="收货人" width="100">
      <template #default="scope">
        <el-tag>{{ scope.row.receiver }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="收货人电话" width="120">
      <template #default="scope">
        <el-tag>{{ scope.row.receiver_phone }}</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="下单时间" width="160">
      <template #default="scope">
        <el-tag>{{ scope.row.create_time }}</el-tag>
      </template>
    </el-table-column>
    <!-- 操作列 -->
    <el-table-column label="操作">
      <template #default="scope">
        <!-- <el-button size="small" @click="handleEdit(scope.$index, scope.row)">
          编辑
        </el-button>
        <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
        >
          删除
        </el-button> -->
        <el-button
            size="small"
            type="success"
            @click="confirmOrder(scope.row)"
            :disabled="scope.row.order_status === 1 || scope.row.order_status === 2"
        >
          确认订单
        </el-button>
        <el-button
            size="small"
            type="warning"
            @click="cancelOrder(scope.row)"
            :disabled="scope.row.order_status !== 0"
        >
          取消订单
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页组件 -->
  <el-pagination
      v-model:current-page="searchObj.current"
      v-model:page-size="searchObj.limit"
      :page-sizes="[10, 20, 30, 50]"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style="margin-top: 10px;"
  />

  <!-- 编辑弹窗（已注释） -->
  <!-- <el-dialog v-model="editWinVisible" title="编辑订单" width="500">
    <el-form :model="obj">
      <el-form-item label="订单编号" :label-width="100">
        <el-input v-model="obj.order_no" autocomplete="off" />
      </el-form-item>
      <el-form-item label="客户ID" :label-width="100">
        <el-select v-model="obj.user_id" placeholder="请选择客户" style="width: 240px">
          <el-option
              v-for="item in users"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          ></el-option>
        </el-select>
        <div style="margin-top:8px;color:#999">当前选择：{{ formUserName }}</div>
      </el-form-item>
      <el-form-item label="订单总金额" :label-width="100">
        <el-input v-model="obj.total_amount" autocomplete="off" />
      </el-form-item>
      <el-form-item label="订单状态" :label-width="100">
        <el-select v-model="obj.order_status" placeholder="请选择订单状态">
          <el-option label="未确认" value="0"></el-option>
          <el-option label="已确认" value="1"></el-option>
          <el-option label="已取消" value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="收货地址" :label-width="100">
        <el-input v-model="obj.shipping_address" autocomplete="off" />
      </el-form-item>
      <el-form-item label="收货人" :label-width="100">
        <el-input v-model="obj.receiver" autocomplete="off" />
      </el-form-item>
      <el-form-item label="收货人电话" :label-width="100">
        <el-input v-model="obj.receiver_phone" autocomplete="off" />
      </el-form-item>
      <el-form-item label="下单时间" :label-width="100">
        <el-input v-model="obj.create_time" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="editCancel">取消</el-button>
        <el-button type="primary" @click="editCommit">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog> -->

  <!-- 新增弹窗（已注释） -->
  <!-- <el-dialog v-model="addWinVisible" title="新增订单" width="500">
    <el-form :model="obj">
      <el-form-item label="订单编号" :label-width="100">
        <el-input v-model="obj.order_no" autocomplete="off" />
      </el-form-item>
      <el-form-item label="客户ID" :label-width="100">
        <el-select v-model="obj.user_id" placeholder="请选择客户" style="width: 240px">
          <el-option
              v-for="item in users"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          ></el-option>
        </el-select>
        <div style="margin-top:8px;color:#999">当前选择：{{ formUserName }}</div>
      </el-form-item>
      <el-form-item label="订单总金额" :label-width="100">
        <el-input v-model="obj.total_amount" autocomplete="off" />
      </el-form-item>
      <el-form-item label="订单状态" :label-width="100">
        <el-select v-model="obj.order_status" placeholder="请选择订单状态">
          <el-option label="未确认" value="0"></el-option>
          <el-option label="已确认" value="1"></el-option>
          <el-option label="已取消" value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="收货地址" :label-width="100">
        <el-input v-model="obj.shipping_address" autocomplete="off" />
      </el-form-item>
      <el-form-item label="收货人" :label-width="100">
        <el-input v-model="obj.receiver" autocomplete="off" />
      </el-form-item>
      <el-form-item label="收货人电话" :label-width="100">
        <el-input v-model="obj.receiver_phone" autocomplete="off" />
      </el-form-item>
      <el-form-item label="下单时间" :label-width="100">
        <el-input v-model="obj.create_time" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addCancel">取消</el-button>
        <el-button type="primary" @click="addCommit">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog> -->
</template>

<style scoped>
.el-table {
  margin-top: 10px;
}
</style>